package com.example.springbootinit.controller;

import com.example.springbootinit.domain.User;
import com.example.springbootinit.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;
@Slf4j
    @RestController
    public class UserController {
        @Autowired
        private UserService userService;
        // 使用路径变量 + GET方法
        @GetMapping("/user/{id}")
        public ResponseEntity<User> getUserById(
                @PathVariable Long id) {

            // 日志记录请求
            log.info("查询用户信息, id={}", id);

            // 调用Service层（假设返回Optional<User>）
            Optional<User> userOptional = userService.selectById(id);

            // 存在则返回200 + 用户数据；不存在返回404
            return userOptional
                    .map(ResponseEntity::ok)
                    .orElseGet(() -> ResponseEntity.notFound().build());
        }

    //添加用户
    @PostMapping("/user/insert")
    public ResponseEntity<String> addUser(@RequestBody User user) {
        boolean isSuccess = userService.insert(user);
        if (isSuccess) {
            return ResponseEntity.status(HttpStatus.CREATED).body("用户添加成功");
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("用户添加失败");
        }
    }


}

